package com.data.interceptor;

import com.data.Const;
import com.data.controller.AuthController;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by silenceholic on 2017/5/4.
 */
public class AuthInterceptorAdapter extends HandlerInterceptorAdapter {

    private static final Logger logger = LoggerFactory.getLogger(AuthInterceptorAdapter.class);

    public AuthInterceptorAdapter() {
        super();
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            Object sysUser = request.getSession().getAttribute(Const.SESSION_USER);
            HandlerMethod method = (HandlerMethod) handler;

            if (null != sysUser) {
//                Auth auth = (Auth) sysUser;
//                if (null != null) {

//                    List<Menu> menu = Arrays.asList(auth.getMenu());

//                    if (checkRights(menu, request, handler)) {
//
//                        return true;
//                    } else {
//                        //跳转权限页面
//                        response.sendRedirect( Const.URL_ERROR_403);
//                        return false;
//                    }
//                }
                return true;
            } else {
                if (request.getRequestURI().indexOf("/index.htm") > 0 || request.getRequestURI().equalsIgnoreCase("/")/*首页*/) {
                    response.sendRedirect("/auth/login.htm");
                } else {
                    String urlEncode;
                    if (StringUtils.isNotEmpty(request.getQueryString())) {
                        urlEncode = java.net.URLEncoder.encode(request.getRequestURI() + "?" + request.getQueryString(), "utf-8");
                    } else {
                        urlEncode = java.net.URLEncoder.encode(request.getRequestURI(), "utf-8");
                    }
                    response.sendRedirect("/auth/login.htm?back=" + urlEncode);
                }
                return false;
            }
        } catch (Exception e) {
//            LOGGER.error("Auth intercept error.", e);
            return false;
        }
    }

//    private boolean checkRights(List<Menu> menu, HttpServletRequest request, Object handler) {
//
//        boolean flag = CollectionUtils.isEmpty(menu);
//
//        if (!flag) {
//            flag = false;
//
//            String requestUrl = request.getRequestURI();
//
//            if (org.apache.commons.lang.StringUtils.equalsIgnoreCase(requestUrl, homeResource.getHomeUrl())) {
//                flag = true;//如果是首页则是登陆页面
//            } else {
//                if (requestUrl.indexOf(".do") > 0 || requestUrl.equalsIgnoreCase("/") || checkIgnoreUrl(requestUrl)) {//如果是.do请求或者是/首页,并且不需要权限验证的页面允许请求
//                    flag = true;
//                } else {
//                    OK:
//                    for (Menu m : menu) {
//                        if (m.isHasMenu()) {
//                            if (requestUrl.indexOf(m.getMENU_URL()) >= 0 && m.getMENU_ORDER() != "-1") {
//                                flag = true;
//                                break;
//                            }
//                            for (Menu sm : m.getSubMenu()) {
//                                if (sm.isHasMenu() && requestUrl.indexOf(sm.getMENU_URL()) >= 0 && !sm.getMENU_ORDER().equalsIgnoreCase("-1")) {
//                                    flag = true;
//                                    break OK;
//                                }
//                            }
//                        }
//                    }
//                    if (!flag) {//如果不在以上二级菜单内，但是属于某一菜单下，也允许访问
//                        flag = checkIgnoreUrlMap(menu, requestUrl);
//                    }
//                }
//            }
//        }
//        return flag;
//    }


//    private boolean checkMenuId(List<Menu> menu, String menuId) {
//        boolean flag = false;
//
//        OK:
//        for (Menu m : menu) {
//            if (m.isHasMenu() && m.getMENU_ID().equals(menuId)) {
//                flag = true;
//                break;
//            }
//
//            for (Menu sm : m.getSubMenu()) {
//                if (sm.isHasMenu() && sm.getMENU_ID().equals(menuId)) {
//                    flag = true;
//                    break OK;
//                }
//            }
//        }
//        return flag;
//    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }

    @Override
    public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        super.afterConcurrentHandlingStarted(request, response, handler);
    }
}
